import { PackageManagerTabs } from "../../src/theme/PackageManagerTabs";

# Javascript Api

`Farm` provides a comprehensive set of APIs for development servers, compilers, watchers, etc. Developers can use these APIs by importing the `@farmfe/core` package.

Install the `@farmfe/core` package:

<PackageManagerTabs command="pnpm add @farmfe/core@latest" />

## Start

The `start` method is used to quickly launch the development server.

After calling the `start` method, you can see the log information of the available `ip` address in the current console. By default, it compiles the `index.html` file in the current directory.

Type:
  
```typescript
start(options: InlineConfig): Promise<void>
```
Basic example:

```javascript
import { start, logger } from "@farmfe/core";
try {
  await start({
    compilation: {
      output: {
        publicPath: "/dist"
      },
      input: {
        index: "./base.html"
      }
    },
    server: {
      port: 6532,
      hmr: {
        path: "/__farm_hmr",
      }
    },
    plugins: [
      '@farmfe/plugin-react',
      '@farmfe/plugin-sass'
    ],
  });
} catch (error) {
  logger.error(`Failed to start server:\n ${error.stack}`);
  process.exit(1);
}

```

another way is use more deep api to start server: 



```javascript
import {
  createCompiler,
  createDevServer,
  resolveConfig
} from '@farmfe/core';

const resolveUserConfig = await resolveConfig({
      compilation: {
      output: {
        publicPath: "/dist"
      },
      input: {
        index: "./base.html"
      }
    },
    server: {
      port: 6532,
      hmr: {
        path: "/__farm_hmr",
      }
    },
    plugins: [
      '@farmfe/plugin-react',
      '@farmfe/plugin-sass'
    ],
})

// create compiler
const compiler = await createCompiler(resolveUserConfig);
const server = await createDevServer(compiler, resolveUserConfig);
server.listen();
```

## Build
The build method is used to build for the production environment.

After calling the build method, it defaults to building browser artifacts and generates a dist folder in the current directory. If you need to build artifacts for different environments and versions, such as node, node-next, browser, browser-es2017, etc., you can configure it by checking output targetEnv.

Type:

```typescript
build(options: InlineConfig): Promise<void>
```
Basic example:

```javascript
import { build, logger } from "@farmfe/core";
try {
  await build(options);
} catch (error) {
  logger.error(`error during build:\n ${error.stack}`);
  process.exit(1);
}
```
## Watch
The watch method provides real-time updates for the compilation of the current project, equivalent to npx farm build --watch. Generally used in the node environment.

Type:

```typescript
watch(options: InlineConfig): Promise<void>
```
Basic example:

```javascript
import { watch, logger } from "@farmfe/core";
try {
  await watch(defaultOptions);
} catch (error) {
  logger.error(`error during watch project:\n ${error.stack}`);
  process.exit(1);
}
```
## Preview
The preview method starts a preview server for previewing production artifacts. Make sure to have built the artifacts using the build method and have the correct production artifacts.

Type:

```typescript
preview(options: InlineConfig): Promise<void>
```
Basic example:

```javascript
import { preview, logger } from "@farmfe/core";
try {
  await preview(defaultOptions);
} catch (error) {
  logger.error(`Failed to start preview server:\n ${error.stack}`);
  process.exit(1);
}
```
## Clean
The clean method clears the cache generated by the farm incremental build. If you have issues with the incremental build causing crashes due to unforeseen or undiscovered problems, clearing the cache might help.

:::warning
If there are problems with the incremental build causing crashes that are not resolved by clearing the cache, please submit an issue on GitHub.
:::

Type:

```typescript
clean(options: InlineConfig): Promise<void>
```
Basic example:

```javascript
import { clean, logger } from "@farmfe/core";
try {
  await clean(defaultOptions);
} catch (error) {
  logger.error(`Failed to clean cache:\n ${error.stack}`);
  process.exit(1);
}
```

## loadEnv
Load environment variables from the .env file.

```ts
type LoadEnvFunc = (
  mode: string,
  envDir: string,
  prefixes: string | string[] = ['FARM_', 'VITE_']
) => [env: Record<string, string>, existsEnvFiles: string[]];
```

* `mode` is `development`, `production` or any string. `loadEnv` will try load `[``.env``, ``.env.local``, ``.env.${mode}``, ``.env.${mode}.local``]` for `envDir`.
* `envDir` is the directory where the `.env` file is located.
* `prefixes` is the prefix of the environment variable. The default value is `['FARM_', 'VITE_']`. Env variables with these prefixes will be injected into `define` automatically.

```js
const [env, files] = loadEnv('development', '/path/to/project/env');
// use env
```

## createDevServer
The createDevServer method is used to start a local development server. You need to instantiate the Server object first and pass the compiler as a parameter.

Type:

```typescript
createDevServer(options: DevServerOptions): Promise<void>
```
Basic example:

```javascript
import { Server } from "@farmfe/core";
const server = new Server();
await server.createDevServer(options);
server.listen()
```
## createPreviewServer
Create a preview server for previewing production artifacts.

Type:

```typescript
createPreviewServer(options: DevServerOptions): Promise<void>
```
Basic example:

```javascript

import { Server } from "@farmfe/core";
const server = new Server();
await server.createPreviewServer(options);
```
## getCompiler
Get the current development server's compiler instance. Pass the compiler as a parameter when instantiating the Server.

Type:

```typescript

getCompiler(): Compiler
```
Basic example:

```javascript

import { Server, Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const server = new Server({
  compiler
});
const compilerInstance = server.getCompiler();
```
## close
Close all servers and WebSocket services opened by createDevServer.

Basic example:

```javascript

import { Server } from "@farmfe/core";
const server = new Server();
await server.createDevServer(options);
server.listen()
await server.close();
```
## Compiler
The Compiler provides a set of compiler APIs. You can create a compiler instance by instantiating Compiler.

Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile();
```
### compile
Asynchronously start the compilation process. Returns a Promise.

:::note
If specific environment variables are set (process.env.FARM_PROFILE), it performs a synchronous compilation.
:::

Type:

```typescript

compile(): Promise<void>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile();
```
### compileSync
Synchronously start the compilation process.

Type:

```typescript

compileSync(): void
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
compiler.compileSync();
```
### traceDependencies
Trace dependencies between files. Returns an array of all dependencies for the provided input in the compiler configuration. Useful for restarting compilation based on file dependencies.

Type:

```typescript

traceDependencies(): Array<string>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";

const config = {
  input: "./farm.config.js"
}
const compiler = new Compiler(config);
const dependencies = compiler.traceDependencies();
```
Returns an array of paths representing all dependencies.

### update
Update compilation based on the provided paths. Returns a Promise resolving to a JsUpdateResult. If compilation is already in progress, it waits for completion and updates. If ignoreCompilingCheck is set to true, it won't check the compilation status.

```typescript

type JsUpdateResult = {
  success: boolean
  errors: Array<Error>
  warnings: Array<Error>
}

update(paths: Array<string>, sync: boolean, ignoreCompilingCheck: boolean): JsUpdateResult
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = await compiler.update(paths, true, true);
```
### hasModule
Pass a path to determine if the current path is within the modules compiled by the compiler.

Type:

```typescript

hasModule(path: string): boolean
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.hasModule(path);
```
### getParentFiles
Retrieve the current file that a module import with the module import name (id) or resolved path identifier (resolvedPath) imports.

Type:

```typescript

getParentFiles(resolvedPath: string): Array<string>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.getParentFiles(resolvedPath);
```
### resources
Return all resources compiled by the compiler.

Type:

```typescript

type Resource = {
  path: string
  buffer: Buffer
}
resources(): Array<Resource>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resources();
```
### Resource
Return the buffer of the current artifact based on the given file.

Type:

```typescript

resource(path: string): Buffer | null
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resource(path);
```
### writeResourcesToDisk
Write resources to disk based on the configured output path.

Type:

```typescript

writeResourcesToDisk(): void
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
compiler.writeResourcesToDisk();
```
### removeOutputPathDir
Remove the output path directory.

Type:

```typescript

removeOutputPathDir(): void
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
compiler.removeOutputPathDir();
```
### resolvedWatchPaths
Return resolved watch paths.

Type:

```typescript

resolvedWatchPaths(): Array<string>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resolvedWatchPaths();
```
### resolvedModulePaths
Return resolved module paths relative to the provided root path.

Type:

```typescript

resolvedModulePaths(rootPath: string): Array<string>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
await compiler.compile()
const result = compiler.resolvedModulePaths(rootPath);
```
### onUpdateFinish
Add a callback to be executed after the update process is complete.

Type:

```typescript

onUpdateFinish(callback: (...args: any[]) => any): void
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
compiler.onUpdateFinish(callback);
```
### outputPath
Return the resolved output path.

Type:

```typescript

outputPath(): string
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.outputPath();
```
### addExtraWatchFile
Add extra watch files for the compiler.

Type:

```typescript

addExtraWatchFile(rootPath: string, filePath: string[]): void
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
compiler.addExtraWatchFile(rootPath, filePath);
```
### modules
Return an array of objects representing file module resolutions.

Type:

```typescript

export interface Module {
  id: string
  moduleType: string
  moduleGroups: Array<string>
  resourcePot?: string
  sideEffects: boolean
  sourceMapChain: Array<string>
  external: boolean
  immutable: boolean
}
modules(): Array<Module>
```
Basic example:

```javascript

import { Compiler } from "@farmfe/core";
const compiler = new Compiler(config);
const result = compiler.modules();
```
